<?php

class CommonFunctionService extends AbstractService
{
    const PrivateKey = 'a4FgAs1d7Sg8Ndfs6c2def5360dd26';
    /**
     * @var CommonFunctionService
     */
    private static $instance;

    /**
     * Get instance of CommonFunctionService.
     *
     * @return CommonFunctionService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new CommonFunctionService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理创建时的逻辑
     *
     * @param int $shardId
     * @return void
     */
    public function handleCreate($shardId)
    {

    }

    /**
     * 用户登录后触发逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {

    }

    /**
     * 提供当前 service 数据
     * @param int $userId
     * @param bool $visitMode
     * @return mixed|void
     */
    public function info($userId, $visitMode = false)
    {

    }

    /**
     * MD5校验通用接口
     * @param $reqSign
     * @param $reqTime
     * @return bool
     */
    public function checkMd5($reqSign,$reqTime)
    {
        $mineSign = md5(self::PrivateKey.$reqTime);

        $signLength = strlen($mineSign);
        $halfLength = floor($signLength/2);//向下取整
        $preSign = substr($mineSign,0,$signLength-$halfLength);
        $nextSign = substr($mineSign,$halfLength);

        $checkSign = $nextSign.$preSign;//进行互换
        if ($checkSign != $reqSign){
            return false;
        }

        return true;
    }

    /**
 * 缓存标记验证
 * @param $redisKey
 * @param $userId
 * @param $reqTime
 * @return bool
 */
    public function redisFlagCheck($redisKey,$userId,$reqTime)
    {
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $redisValue = $redisDb->get($redisKey.$userId);

        if ($redisValue && $reqTime <= $redisValue){
            return false;
        }

        $redisDb->set($redisKey.$userId,$reqTime);
        return true;
    }

    /**
     * 验证活动是否开启接口
     * @param $userId
     * @param $activityId
     * @param $activityType
     * @param $reqTime
     * @return array
     */
    public function checkActivityState($userId, $activityId, $activityType,$reqTime)
    {
        $res = array(
            'code' => 0,
            'start' => 0,
            'end' => 0
        );

        //获取玩家平台数据
        $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
        $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];

        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);
        $startTime = strtotime($activity[$platformPre.'TriggerTime']);
        $endTime = strtotime($activity[$platformPre.'EndTime']);
        if (empty($startTime) || empty($endTime)){
            $startTime = $activity['startTime'];
            $endTime = $activity['endTime'];
        }

        if ($startTime > $reqTime) {
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['START_ERR'];//开始时间错误

        }
        if ($endTime <= $reqTime) {
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['END_ERR'];//结束时间错误
        }

        if ($activity['type'] != $activityType) {
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['ACT_TYPE_ERR'];//活动类型错误
        }

        $res['start'] = $startTime;
        $res['end'] = $endTime;
        return $res;
    }

    /**
     * 权重随机
     * @param $weighArr
     * @return mixed
     */
    public function weightRandom($weighArr)
    {
        $weight = 0;
        $temp = array();
        foreach ($weighArr as $data){
            $weight += $data['weight'];
            for ($i=0;$i<$data['weight'];$i++){
                $temp[] = $data;
            }
        }

        $use = rand(0, $weight-1);
        return $temp[$use];
    }

    /**
     * 获取玩家展示矿数据
     * @param $userId
     * @param $score
     * @param $type
     * @return array
     * @throws SzException
     */
    public function getUserInfo($userId,$score,$type) {
        /**
         * @var ModuleProfileVo $profileInfo
         * @var ModuleProfileInfoVoList $profileInfoList
         */
        $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
        $res = array(
            'userId' => $userId,
            'userLevel' => UserService::get()->getUserLevel($userId),
            'townName' => UserService::get()->getTownName($userId, $profileInfoList),
            'headImgId' => UserService::get()->getHeadIcon($userId, $profileInfoList),
            'gender' => UserService::get()->getGender($userId,$profileInfoList),
            'score' => $score,
            'flowerLevel' => UserService::get()->getFlowerLevel($userId,$profileInfoList),
            'flowerLevelExpireTime' => UserService::get()->getFlowerLevelExpireTime($userId,$profileInfoList),
        );

        //特殊数据添加
        if ($type == 1){//中秋节获取头像框所属
            $profileInfo = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_HEAD_FRAME,false);
            if (!$profileInfo){
                $res['headFrame'] = 0;
            }
            else{
                $res['headFrame'] = $profileInfo->getInfo();
            }
        }

        return $res;
    }

    /**
     * 上报资源使用明细
     * @param $funcId
     * @param $userId
     * @param $type
     * @param $itemIdStr
     * @param $operation
     * @return bool
     */
    public function reportResourceUseDetails($funcId,$userId,$type,$itemIdStr,$operation)
    {
        $logType = '';
        if ($type == 0){
            $logType = GameConst::LOG_TYPE_RESOURCE_INPUT;// 消耗记录
        }
        else{
            $logType = GameConst::LOG_TYPE_RESOURCE_OUTPUT;// 收获记录
        }

        if ($logType != ''){
            StatisticsService::get()->saveLog($userId, $logType, array(
                'clientData' => array(
                    'tid' => 'Module:newResourceReport|action:recordResource|',
                    'item' => $operation.'|'.$itemIdStr,
                    'value' => 1,
                    'value2' => $funcId,
                )
            ));
        }

        return true;
    }

}